package elitech.vietnam.weatherfashion.tabs.styler;

import java.io.IOException;
import java.util.List;

import android.os.AsyncTask;
import android.os.Bundle;
import android.text.Html;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.TextView;

import com.handmark.pulltorefresh.library.PullToRefreshBase;
import com.handmark.pulltorefresh.library.PullToRefreshBase.Mode;
import com.handmark.pulltorefresh.library.PullToRefreshBase.OnRefreshListener2;
import com.handmark.pulltorefresh.library.PullToRefreshGridView2;
import com.koushikdutta.urlimageviewhelper.UrlImageViewHelper;

import elitech.vietnam.weatherfashion.MainActivity;
import elitech.vietnam.weatherfashion.R;
import elitech.vietnam.weatherfashion.WFApplication;
import elitech.vietnam.weatherfashion.backgroundtask.ButtonAskFriendTask;
import elitech.vietnam.weatherfashion.config.Const;
import elitech.vietnam.weatherfashion.config.GlobalValue;
import elitech.vietnam.weatherfashion.config.Utils;
import elitech.vietnam.weatherfashion.dialog.DialogUserInfo;
import elitech.vietnam.weatherfashion.dialog.PicPickerDialog;
import elitech.vietnam.weatherfashion.dialog.WarningDialog;
import elitech.vietnam.weatherfashion.dto.MemberDTO;
import elitech.vietnam.weatherfashion.dto.PostDTO;
import elitech.vietnam.weatherfashion.libs.multicolumlist.MultiColumnListView;
import elitech.vietnam.weatherfashion.service.PHPSoapServiceCaller;
import elitech.vietnam.weatherfashion.tabs.AbstractFragment;
import elitech.vietnam.weatherfashion.widget.NotifyButton;

public class StylerDetailFragment extends AbstractFragment implements View.OnClickListener, OnRefreshListener2<MultiColumnListView> {

	private static final int NUMTASK = 2;
	
	private PostDTO post;
	private MemberDTO member;
	private int memId = -1;
	private List<PostDTO> posts;
	private TextView text_username, text_userstatus, mTextHeader;
	private ImageView image_useravatar;
	private PullToRefreshGridView2 gridview_main;
	private StylerDetailGridAdapter mAdapter;
	private Button button_camera, button_addfriend;
	private NotifyButton button_notification;

	boolean isPullUp = false;
	int mTask = 0;
	
	public static StylerDetailFragment init(PostDTO post) {
		StylerDetailFragment fr = new StylerDetailFragment();
		fr.post = post;
		return fr;
	}

	public static StylerDetailFragment init(int memId) {
		StylerDetailFragment fr = new StylerDetailFragment();
		fr.memId = memId;
		return fr;
	}

	@Override
	public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
		View view = inflater.inflate(R.layout.styler_mem, container, false);
		setupView(view);

		button_addfriend = (Button) view.findViewById(R.id.meminfo_button_addfriend);
		text_username = (TextView) view.findViewById(R.id.meminfo_textview_username);
		text_userstatus = (TextView) view.findViewById(R.id.meminfo_textview_userstatus);
		image_useravatar = (ImageView) view.findViewById(R.id.meminfo_image_useravatar);
		gridview_main = (PullToRefreshGridView2) view.findViewById(R.id.layout_main);
		button_camera = (Button) view.findViewById(R.id.stylerdetail_button_camera);
		mTextHeader = (TextView) view.findViewById(R.id.stylerdetail_text_header);
		button_notification = (NotifyButton) view.findViewById(R.id.button_notification);
		
		((MainActivity) getActivity()).setCurrentNotifyButton(button_notification);

		if (!isAdded())
			return null;
		
		onLoading(true);
		mTask = 0;
		
//		mTextHeader.setText(Html.fromHtml(getString(R.string.stylertitle)));
		button_camera.setOnClickListener(this);

		MemberDTO m = GlobalValue.getInstance(getActivity()).readUserInfo();
		if (m == null)
			button_notification.setVisibility(View.GONE);
		else 
			button_notification.setVisibility(View.VISIBLE);
		//button_notification.setOnClickListener(this);

		if ((posts == null || posts.isEmpty()))
			new GetStylerPostTask().execute();
		else
			loadPost();
		if (member == null)
			new GetMemberTask().execute();
		else {
			loadMember();
			loadButtonFriend();
		}
		return view;
	}
	
	@Override
	public void onPause() {
		super.onPause();
		gridview_main.onRefreshComplete();
	}

	@Override
	public void onDestroyView() {
		gridview_main = null;
		mAdapter = null;
		posts = null;
		member = null;
		super.onDestroyView();
	}

	public void loadPost() {
		finishLoading();
		if (gridview_main == null)
			return;
		if (posts.isEmpty()) {
			onNoData(true);
			return;
		}
		mAdapter = new StylerDetailGridAdapter(this, member, R.layout.styler_grid_item, posts);
		gridview_main.setMode(Mode.PULL_FROM_END);
		gridview_main.setOnRefreshListener(this);
		gridview_main.setAdapter(mAdapter);
	}

	private void finishLoading() {
		mTask +=1;
		if (mTask == NUMTASK)
			onLoading(false);
	}

	public void loadMember() {
		finishLoading();
		if (member == null)
			return;
		
		String title = getString(R.string.stylertitle);
		String mName = (member.getMemberName().equals("")) ? member.getMemberUsername() : member.getMemberName();
		title = title.replace(getString(R.string.styler), getString(R.string.style));
		title = title.replace("TODAY", mName);
		mTextHeader.setText(Html.fromHtml(title));
		// ImageLoader.getInstance().displayImage(AppConfig.SERVER_IMAGE_URL +
		// this.member.getMemberPic(), image_useravatar);
		UrlImageViewHelper.setUrlDrawable(image_useravatar, Const.SERVER_IMAGE_URL + this.member.getMemberPic(), R.drawable.avatar);
		text_username.setText(this.member.getMemberName());
		text_userstatus.setText(this.member.getMemberProfile());
		image_useravatar.setOnClickListener(this);
		
	}

	public void loadButtonFriend() {
		MemberDTO user = GlobalValue.getInstance(getActivity()).readUserInfo();
		if (member == null || WFApplication.getInstance().userFriends == null || user == null) {
			button_addfriend.setVisibility(View.GONE);
			return;
		}
		if (member.getId() == user.getId()) {
			button_addfriend.setVisibility(View.GONE);
			return;
		}
		button_addfriend.setVisibility(View.VISIBLE);
		if (Utils.isFriend(member.getId())) {
			button_addfriend.setEnabled(false);
			button_addfriend.setBackgroundResource(R.drawable.button_friend_p);
			button_addfriend.setCompoundDrawablesWithIntrinsicBounds(getResources().getDrawable(R.drawable.button_friend_icon_p), null, null, null);
			button_addfriend.setTextColor(getResources().getColor(R.color.color_lightbutton_p));
		} else {
			button_addfriend.setOnClickListener(this);
		}
	}

	@Override
	public void onClick(View v) {
		MemberDTO user = GlobalValue.getInstance(getActivity()).readUserInfo();
		switch (v.getId()) {
		case R.id.meminfo_button_addfriend:
			new ButtonAskFriendTask(getActivity(), button_addfriend).execute(user.getId(), member.getId());
			break;

		case R.id.stylerdetail_button_camera:
			if (user == null) {
				Utils.openLogin(getActivity());
			} else
				new PicPickerDialog(getActivity(), this).show();
			break;

		case R.id.meminfo_image_useravatar:
			new DialogUserInfo(getActivity(), member).show();
			break;

		case R.id.button_notification:
			Log.w("Notification", "Num Count: " + WFApplication.getInstance().mListNoti.size());
			((MainActivity) getActivity()).mNotiWindow.showAsDropDown(button_notification);
			((MainActivity) getActivity()).mNotiWindow.notifyDataChanged();
			button_notification.setNumber(0);
			break;

		default:
			break;
		}
	}

	class GetStylerPostTask extends AsyncTask<Integer, Integer, Boolean> {
		@Override
		protected Boolean doInBackground(Integer... params) {
			PHPSoapServiceCaller appService = new PHPSoapServiceCaller();
			MemberDTO user = GlobalValue.getInstance(getActivity()).readUserInfo();
			int myId = user == null ? -1 : user.getId();
			int n = post != null ? post.getStoreId() : memId;
			try {
				posts = appService.getFashionMemberLikeCountry(n, myId, Const.COUNTRY_CODE, 0, Const.LOADMORE_PAGE_ITEMCOUNT);
			} catch (IOException e) {
				return false;
			}
			return null;
		}

		@Override
		protected void onPostExecute(Boolean result) {
			super.onPostExecute(result);
			if (!isAdded())
				return;
			if (result != null) {
				new WarningDialog.Builder(getActivity())
				.setOnClick(new WarningDialog.OnButtonClick() {
					@Override
					public void doClick() {
						getActivity().onBackPressed();
					}
				}).createTimeOutDialog().show();
				return;
			}
			loadPost();
			if (member != null)
				loadMember();
		}
	}

	class GetMemberTask extends AsyncTask<Integer, Integer, Boolean> {
		@Override
		protected Boolean doInBackground(Integer... params) {
			PHPSoapServiceCaller appService = new PHPSoapServiceCaller();
			int n = post != null ? post.getStoreId() : memId;
			try {
				member = appService.getInfoMember(n);
			} catch (IOException e) {
				return false;
			}
			return null;
		}

		@Override
		protected void onPostExecute(Boolean result) {
			super.onPostExecute(result);
			if (!isAdded())
				return;
			if (result != null) {
				new WarningDialog.Builder(getActivity())
				.setOnClick(new WarningDialog.OnButtonClick() {
					@Override
					public void doClick() {
						getActivity().onBackPressed();
					}
				}).createTimeOutDialog().show();
				return;
			}
			loadMember();
			loadButtonFriend();
			if (posts != null)
				loadPost();
		}
	}

	@Override
	public void onPullDownToRefresh(PullToRefreshBase<MultiColumnListView> refreshView) {
		new LoadMoreItem().execute();
	}

	@Override
	public void onPullUpToRefresh(PullToRefreshBase<MultiColumnListView> refreshView) {
		new LoadMoreItem().execute();
	}
	
	class LoadMoreItem extends AsyncTask<Integer, Integer, List<PostDTO>> {
		@Override
		protected List<PostDTO> doInBackground(Integer... params) {
			PHPSoapServiceCaller service = new PHPSoapServiceCaller();
			MemberDTO user = GlobalValue.getInstance(getActivity()).readUserInfo();
			int n = (user != null) ? user.getId() : -1;
			int m = post != null ? post.getStoreId() : memId;
			List<PostDTO> list = null;
			try {
				list = service.getFashionMemberLikeCountry(m, n, Const.COUNTRY_CODE, posts.size(), Const.LOADMORE_PAGE_ITEMCOUNT);
			} catch (IOException e) {
				e.printStackTrace();
				return null;
			}
			return list;
		}
		@Override
		protected void onPreExecute() {
			super.onPreExecute();
		}
		@Override
		protected void onPostExecute(List<PostDTO> result) {
			super.onPostExecute(result);
			if (gridview_main != null)
				gridview_main.onRefreshComplete();
			if (result == null) {
				new WarningDialog.Builder(getActivity())
				.setOnClick(new WarningDialog.OnButtonClick() {
					@Override
					public void doClick() {
						getActivity().onBackPressed();
					}
				}).createTimeOutDialog().show();
				return;
			}
			if (result.isEmpty()) {
				if (gridview_main != null) {
					gridview_main.setMode(Mode.DISABLED);
					gridview_main.setOnRefreshListener((OnRefreshListener2<MultiColumnListView>)null);
				}
				return;
			}
			if (posts != null)
				posts.addAll(result);
			if (mAdapter != null)
				mAdapter.notifyDataSetChanged();
		}
	}
}
